<template>
  <div>
    <el-scrollbar :style="{height: bodyHeight+'px'}">
      <el-collapse v-model="activeNames" accordion  v-loading="loading" :element-loading-text="loadingText">
        <el-collapse-item title="Order List" name="1"  style="padding-left: 15px;">
          <el-tag style="margin: 5px 5px;min-width:215px;"
                  v-for="(tag, index) in dataList"
                  closable
                  :type="(index+1 % 1 == 0) ? 'success' : (index % 2 == 0) ? 'info' : (index % 3 == 0) ? 'warning' : (index % 4 == 0) ? 'danger' : ''"
                  @click="clickTag(tag.id,index)" @close="closeTag(tag.id)">
            GuestName:{{tag.guestName}}.[{{tag.startDate}} to {{tag.endDate}}]
          </el-tag>
        </el-collapse-item>
        <el-collapse-item title="Add Order" name="2" style="padding-left: 15px;">
          <el-form ref="formData" :model="formData"  :rules="rules" label-width="125px">
            <el-form-item label="Physical Room Id" class="form-item-wd">
              <el-input
                placeholder="Physical Room Id"
                v-model="pid"
                :disabled="true">
              </el-input>
            </el-form-item>

            <el-form-item label="Room_Title" class="form-item-wd" >
              <el-input
                placeholder="Please Enter RoomTitle"
                v-model="formData.room_title">
              </el-input>
            </el-form-item>

            <el-form-item label="Order_From" class="form-item-wd" >
              <el-input
                placeholder="Please Enter Order From"
                v-model="formData.order_from">
              </el-input>
            </el-form-item>

            <el-form-item label="CheckIn_Out"  prop="dateRange">
              <div class="block" style="width: 100%">
                <el-date-picker style="width: 70%"
                                v-model="formData.dateRange"
                                type="daterange"
                                align="right"
                                unlink-panels
                                range-separator="to"
                                start-placeholder="CheckIn"
                                end-placeholder="CheckOut"
                                :picker-options="pickerOptions"
                                format="yyyy-MM-dd"
                                value-format="yyyy-MM-dd">
                </el-date-picker>
              </div>
            </el-form-item>

            <el-form-item label="CheckTimeIn_Out"  prop="dateTimeRange">
              <div class="block" style="width: 100%">
                <el-date-picker style="width: 70%"
                                v-model="formData.dateTimeRange"
                                type="datetimerange"
                                align="right"
                                unlink-panels
                                range-separator="to"
                                start-placeholder="CheckTimeIn"
                                end-placeholder="CheckTimeOut"
                                :picker-options="pickerOptions"
                                format="yyyy-MM-dd HH:mm:ss"
                                value-format="yyyy-MM-dd HH:mm:ss">
                </el-date-picker>
              </div>
            </el-form-item>

            <el-row>
              <el-col :span="12">
                <el-form-item label="Logical Room Id"  prop="logical_room_id" class="form-item-wd">
                  <el-select v-model="formData.logical_room_id" placeholder="Please Select A Logical Room Id">
                    <el-option
                      v-for="item in logicRoomList"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value">
                    </el-option>
                  </el-select>
                </el-form-item>

                <el-form-item label="Guest_Name"  prop="logical_room_id" class="form-item-wd">
                  <el-input v-model="formData.guest_name" placeholder="Please Enter Guest Name"/>
                </el-form-item>

                <el-form-item label="Currency"  prop="currency" class="form-item-wd">
                  <el-select v-model="formData.currency" placeholder="Please Select A Currency">
                    <el-option :value="currency"  v-for="(currency, index) in currencies">{{currency}}</el-option>
                  </el-select>
                </el-form-item>

                <el-form-item label="Total_Price"  prop="total_cost" class="form-item-wd">
                  <el-input v-model="formData.total_cost" placeholder="Please Enter Total Price"/>
                </el-form-item>

                <el-form-item label="Clean Fee"  prop="clean_fee" class="form-item-wd">
                  <el-input v-model="formData.clean_fee" placeholder="Please EnterClean Fee"/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="Status"  prop="status" class="form-item-wd">
                  <el-select v-model="formData.status" placeholder="Please Select A Status">
                    <el-option value="NORMAL">NORMAL</el-option>
                    <el-option value="FREE">FREE</el-option>
                    <el-option value="SPECIAL">SPECIAL</el-option>
                    <el-option value="HALF_PRICE">HALF_PRICE</el-option>
                    <el-option value="HOST">HOST</el-option>
                    <el-option value="BNB_ALT">BNB_ALT</el-option>
                    <el-option value="CANCEL_PRE">CANCEL_PRE</el-option>
                  </el-select>
                </el-form-item>

                <el-form-item label="Guest_Number"  prop="guest_num" class="form-item-wd">
                  <el-input v-model="formData.guest_num" placeholder="Please Enter Guest Number"/>
                </el-form-item>

                <el-form-item label="Reservation_Code"  prop="reservation_code" class="form-item-wd">
                  <el-input v-model="formData.reservation_code" placeholder="Please Enter Reservation Code"/>
                </el-form-item>

                <el-form-item label="Platform"  prop="platform" class="form-item-wd">
                  <el-select v-model="formData.platform" placeholder="Please Select A Platform">
                    <el-option :value="item.value" v-for="item in platforms">{{item.label}}</el-option>
                  </el-select>
                </el-form-item>

                <el-form-item label="Service_Fee"  prop="service_fee" class="form-item-wd">
                  <el-input v-model="formData.service_fee" placeholder="Please Enter Service Fee"/>
                </el-form-item>
              </el-col>
            </el-row>

            <el-form-item label="Comment" class="form-item-wd">
              <el-input type="textarea" v-model="formData.comment"></el-input>
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="doSave">Save Changes</el-button>
              <el-button  @click="doClose">Close</el-button>
              <el-button  @click="doReset">Add Data</el-button>
              <el-button type="danger" icon="el-icon-refresh" circle @click="doSynchro"></el-button>
            </el-form-item>
          </el-form>
        </el-collapse-item>
      </el-collapse>

    </el-scrollbar>


  </div>

</template>

<script>
    import config from '@/config';
    import {addModel,searchModel,get,updateModel,deleteModel,addModels,updateModels} from "@/api/model";
    import {getRoomEvents,insertOrder} from "@/api/event";
    import {submitAction} from "@/api/task";

    export default {
        name: "OrderForm",
        props:["pid","_logicRoomList","listingId"],
        data() {
            return {
                model: 'Order', //
                bodyHeight:900,
                parentObj : null, //父对象
                loading:false,
                loadingText:'data load ...',
                totalDays:0,
                id:null,    //当前选中的房态ID
                activeNames: ['1','2'],
                dataList : [],
              logicRoomList:this._logicRoomList,
                currencies: null,
                platforms:null,
                formData: this.getInitFormData(),
                rules: this.getInitRules(),
                pickerOptions: {
                    shortcuts: [{
                        text: 'Last week',
                        onClick(picker) {
                            const end = new Date();
                            const start = new Date();
                            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                            picker.$emit('pick', [start, end]);
                        }
                    }, {
                        text: 'Last month',
                        onClick(picker) {
                            const end = new Date();
                            const start = new Date();
                            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                            picker.$emit('pick', [start, end]);
                        }
                    }, {
                        text: 'Last three months',
                        onClick(picker) {
                            const end = new Date();
                            const start = new Date();
                            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
                            picker.$emit('pick', [start, end]);
                        }
                    }],
                }
            }
        },
        created() {
            const _bodyHeight = document.documentElement.clientHeight || document.body.clientHeight;
            // console.log("bodyHeight="+_bodyHeight);
            this.bodyHeight = _bodyHeight - 65;
          this.currencies = config.CURRENCY
          this.platforms = config.PLATFORM
        },
        mounted(){

        },
        methods: {
            getInitFormData(respData){
              let _id = null;
              let _checkin = null; //"2020-02-19",				Check_In			ok
              let _checkin_time = null; //"2020-02-19 03:00:00",	CheckIn_Time			ok
              let _checkout = null;//"2020-02-20",				Check_Out			ok
              let _checkout_time = null; //"2020-02-20 03:00:00",	CheckOut_Time			ok
              let _clean_fee = '0'; //"150",						Clean Fee
              let _comment = null; //"comment",					Comment			ok
              let _currency = 'JPY'; //"JPY",						Currency
              let _guest_name = null; //"ABNC",					Guest_Name
              let _guest_num = null; //"2",						Guest_Number
              let _logical_room_id = null; //"21819594",			Logical_Room_id
              let _order_from = null; //"asda",					Order_From
              let _physical_room_id = this.pid; //"lilix9",			Physical_Room_id
              let _platform = null;// "offline",					Platform
              let _reservation_code = null; //"NNFMSAFSAK",		Reservation_Code
              let _room_title = null; //"a",						Room_Title
              let _service_fee ="0"; //						Service_Fee
              let _status ="HOST"; //						Status
              let _total_cost = "0"; //					Total_Price
              let _type = "0";//"0";
              let _dateRange = [];
              let _dateTimeRange = [];
              if(respData){
                console.log("clickTag.respData...");
                console.log(respData);
                  _id = respData.id;
                  _checkin = respData.checkin;
                  _checkout = respData.checkout;
                  _checkin_time = respData.checkin_time;
                  _checkout_time = respData.checkout_time;
                  _clean_fee = respData.clean_fee;
                  _comment = respData.comment;
                  _currency = respData.currency;
                  _guest_name = respData.guest_name;
                  _guest_num = respData.guest_num;
                  _logical_room_id = respData.logical_room_id;
                  _order_from = respData.order_from;
                  //_physical_room_id = respData.physical_room_id;
                  _platform = respData.platform;
                  _reservation_code = respData.reservation_code;
                  _room_title = respData.room_title;
                  _service_fee = respData.service_fee;
                  _status = respData.status;
                  _total_cost = respData.total_cost;

                const _startDate = _checkin ?  new Date(_checkin.replace(/-/g, "\/")) : null;
                const _endDate = _checkin ?  new Date(_checkout.replace(/-/g, "\/")): null;
                _dateRange = [_startDate,_endDate];

                const _startTime = _checkin_time ? new Date(_checkin_time.replace(/-/g, "\/")) : null;
                const _endTime = _checkout_time ?  new Date(_checkout_time.replace(/-/g, "\/")) : null;

                _dateTimeRange:[_startTime,_endTime];
              }
              return  {
                id:_id,
                checkin: _checkin, //"2020-02-19",				Check_In			ok
                checkin_time: _checkin_time, //"2020-02-19 03:00:00",	CheckIn_Time			ok
                checkout: _checkout,//"2020-02-20",				Check_Out			ok
                checkout_time: _checkout_time, //"2020-02-20 03:00:00",	CheckOut_Time			ok
                clean_fee: _clean_fee, //"150",						Clean Fee
                comment: _comment, //"comment",					Comment			ok
                currency: _currency, //"JPY",						Currency
                guest_name: _guest_name, //"ABNC",					Guest_Name
                guest_num: _guest_num, //"2",						Guest_Number
                logical_room_id: _logical_room_id, //"21819594",			Logical_Room_id
                order_from: _order_from, //"asda",					Order_From
                physical_room_id: _physical_room_id, //"lilix9",			Physical_Room_id
                platform: _platform,// "offline",					Platform
                reservation_code: _reservation_code, //"NNFMSAFSAK",		Reservation_Code
                room_title: _room_title, //"a",						Room_Title
                service_fee:_service_fee, //						Service_Fee
                status:_status, //						Status
                total_cost:_total_cost, //					Total_Price
                type:_type,
                dateRange:_dateRange,
                dateTimeRange:_dateTimeRange
              };
            },
            getInitRules() {
                const _this = this;
                const custRulesCfg = this.getCustRulesConfig();
                const total_costValid = custRulesCfg.floatValid('Total Price',1,100000);
                const clean_feeValid = custRulesCfg.floatValid('Clean Fee',0,10000);
                const guest_numValid = custRulesCfg.floatValid('Guest Number',1,1000);
                const service_feeValid = custRulesCfg.floatValid('Clean Fee',0,10000);
                return {
                    logical_room_id:[
                      { required: true, message: 'Please Enter Logical_Room_Id', trigger: 'change'}
                    ],
                  status:[
                      { required: true, message: 'Please Select A Status', trigger: 'change'}
                    ],
                    dateRange:[
                        { required: true, message: 'Please Select A CheckIn_Out Date range', trigger: 'change', type: 'array'}
                    ],
                    // dateTimeRange:[
                    //   { required: true, message: 'Please Select A CheckTimeIn_Out Date range', trigger: 'change', type: 'array'}
                    // ],
                    guest_name:[
                      { required: true, message: 'Please Enter Guest Name', trigger: 'blur' },
                      { min: 1, max: 100, message: '1 to 100 characters in length', trigger: 'blur' }
                    ],
                    currency:[
                        { required: true, message: 'Please Select A Currency', trigger: 'change' }
                    ],
                    total_cost:[
                      { required: true,validator: total_costValid,trigger: 'blur' }
                    ],
                    clean_fee:[
                      { required: true,validator: clean_feeValid,trigger: 'blur' }
                    ],
                    guest_num:[
                      { required: true,validator: guest_numValid,trigger: 'blur' }
                    ],
                    reservation_code:[
                      { required: true, message: 'Please Enter Reservation Code', trigger: 'blur' },
                      { min: 1, max: 100, message: '1 to 100 characters in length', trigger: 'blur' }
                    ],
                    platform:[
                      { required: true, message: 'Please Select A Platform', trigger: 'change' }
                    ],
                    service_fee:[
                      { required: true,validator: service_feeValid,trigger: 'blur' }
                    ],
                    comment:[
                        { required: true, message: 'Please Enter Comment', trigger: 'blur' },
                        { min: 1, max: 1000, message: '1 to 1000 characters in length', trigger: 'blur' }
                    ]
                };
            },
            getCustRulesConfig(){
                return {
                    intValid: function(label, min, max){
                        const intValidFun = (rule, value, callback) => {
                            if (!value) {
                                callback(new Error('Please Enter '+label));
                            }
                            try{
                                value = parseInt(value);
                            }catch (e) {
                                callback(new Error(label+' Must be an integer value'));
                            }

                            if (!Number.isInteger(value)) {
                                callback(new Error(label+' Must be an integer value'));
                            }
                            if(min != null && max != null){
                                if(value < min || value > max){
                                    callback(new Error(label+' Must be greater than or equal to '+min+' and less than or equal to '+max));
                                }else{
                                    callback();
                                }
                            }
                            if(min != null && max == null){
                                if (min && min > value) {
                                    callback(new Error(label+' Must be greater than or equal to '+min));
                                } else {
                                    callback();
                                }
                            }

                            if(max != null && min == null){
                                if (max && value > max) {
                                    callback(new Error(label+' Must be less than or equal to '+max));
                                } else {
                                    callback();
                                }
                            }
                        };
                        return intValidFun;
                    },
                    floatValid: function(label, min, max,custCb){
                        const intValidFun = (rule, value, callback) => {
                            if (!value) {
                                callback(new Error('Please Enter '+label));
                            }
                            try{
                                value = parseFloat(value);
                            }catch (e) {
                                callback(new Error(label+' Must be an float value'));
                            }

                            if (!Number.isInteger(value)) {
                                callback(new Error(label+' Must be an float value'));
                            }
                            if(min != null && max != null){
                                if(value < min || value > max){
                                    callback(new Error(label+' Must be greater than or equal to '+min+' and less than or equal to '+max));
                                }else{
                                    if(custCb){
                                        custCb(rule, value, callback);
                                    }else{
                                        callback();
                                    }
                                }
                            }
                            if(min != null && max == null){
                                if (min && min > value) {
                                    callback(new Error(label+' Must be greater than or equal to '+min));
                                } else {
                                    callback();
                                }
                            }

                            if(max != null && min == null){
                                if (max && value > max) {
                                    callback(new Error(label+' Must be less than or equal to '+max));
                                } else {
                                    callback();
                                }
                            }

                        };
                        return intValidFun;
                    },
                };
            },
            refresh(_parentObj){
                console.log("refresh to do ...");
                this.parentObj = _parentObj;
                this.loadDatas();
            },
          setLogicRoomList(_logicRoomList){
              this.logicRoomList = _logicRoomList;
          },
            /**
             * 加载数据
             */
            loadDatas(){
                console.log("loadDatas to do ...");
                this.dataList = this.parentObj.selOrderDatas;
                this.doReset();
            },
            fmtDate2Str(date, fmt){
              if(!fmt) fmt = 'YYYY-MM-DD';
              return  moment(date).format(fmt);
            },
            /**
             * 保存数据
             */
            doSave(){
                console.log("doSave to do ...");
                const _this = this;
                console.log(this.formData);
                let _formData = this.formData;
                for(var key in _formData){
                    const val = _formData[key];
                    if(!val && (val !== 0 || val !== '0')){
                        delete _formData[key];
                    }
                }

                this.$refs['formData'].validate((valid) => {
                    if (valid) {
                        if(_formData.dateRange && _formData.dateRange.length > 0){
                          _formData.checkin = this.fmtDate2Str(_formData.dateRange[0]);
                          _formData.checkout = this.fmtDate2Str(_formData.dateRange[1]);
                        }
                      let _checkin_time = null;
                      let _checkout_time = null;
                      if(_formData.dateTimeRange && _formData.dateTimeRange.length > 0){
                        const dateTimeFmt = 'YYYY-MM-DD HH:mm:ss';
                        _checkin_time = this.fmtDate2Str(_formData.dateTimeRange[0], dateTimeFmt);
                        _checkout_time = this.fmtDate2Str(_formData.dateTimeRange[1], dateTimeFmt);
                      }
                      _formData.checkin_time = _checkin_time;
                      _formData.checkout_time = _checkout_time;
                      if(!_formData.checkin_time) delete  _formData["checkin_time"];
                      if(!_formData.checkout_time) delete  _formData["checkout_time"];
                      delete _formData["dateRange"];
                      delete _formData["dateTimeRange"];
                      _this.loading = true;
                      if(_this.id || this.formData.id){
                        delete _formData["physical_room_id"];
                        delete _formData["type"];
                        updateModel(this.model, _this.id, _formData).then(res => {
                          this.insertData(_formData);  //只有关闭状态才需要重新插入
                        }).catch(reason => {
                          _this.loading = false;
                          console.error(reason);
                        });
                      }else{
                          this.insertData(_formData);
                      }
                    } else {
                        console.log('error submit!!');
                        _this.$message.error('Please Check Input Form Data Has Errors!');
                        return false;
                    }
                });
            },
            insertData(_formData){
                const _this = this;
                this.loading = true;
                delete _formData["dateRange"];
                delete _formData["hourseStatus"];
                insertOrder(_formData).then(res => {
                    this.loading = false;
                    _this.doSynchro();
                    _this.$message({
                        type: 'info',
                        message: 'Save Data Success!'
                    });
                   _this.reloadParentData();
                    console.log(res);
                }).catch(reason => {
                    _this.loading = false;
                    console.log(reason);
                });
            },
            reloadParentData(){
                const _this = this;
                this.doClose();
                _this.parentObj.loadOrderData((list) =>{
                    const _myOrders = list.filter(item => {
                        return item.physical_room_id == _this.pid;
                    });
                    if(!_myOrders || _myOrders.length==0){
                        this.dataList = [];
                        return;
                    }
                    let _dataLiist = [];
                  _myOrders.forEach(item => {
                        const _orders = item.orders;
                        if(!_orders || _orders.length == 0) return;
                        const _arr = _orders.map(item => {
                            return {id:item.id,startDate:item.checkin, endDate:item.checkout,guestName:item.guest_name,platform:item.platform};
                        });
                        _dataLiist = _dataLiist.concat(_arr);
                    });
                    this.dataList = _dataLiist;
                });
            },
            clickTag(id,index){
                const _this = this;
                const _data = this.dataList[index];
                console.log(_data);
                this.id = _data.id;
                this.formData = this.getInitFormData();
                if(this.$refs['formData']) this.$refs['formData'].resetFields();
                this.loading = true;
                get(this.model, _this.id).then(res => {
                  this.loading = false;
                  if(!res.data || !res.data.list || res.data.list.length === 0) return;
                  const respData = res.data.list[0];
                  this.formData = this.getInitFormData(respData);
                }).catch(reason => {
                  _this.loading = false;
                  console.error(reason);
                  //_this.$message.error('Please Check Input Form Data Has Errors!');
                });
            },
            closeTag(_id){
                const _this = this;
                this.id = _id;
                //this.loading = true;
                _this.$message.error({
                  message: 'Order data cannot be deleted!'
                });
                /*
                deleteModel(this.model, _this.id).then(res => {
                    this.loading = false;
                    _this.$message({
                        type: 'info',
                        message: 'Save Data Success!'
                    });
                    _this.reloadParentData();
                }).catch(reason => {
                    _this.loading = false;
                    console.error(reason);
                });
                */
            },
            getParent(){
                return this.parentObj ||  this.$parent;
            },
            doClose(){
                const _parent = this.parentObj ||  this.$parent;
                console.log(_parent);
                _parent.closeDrawer();
            },
            /**
             * 重置表单
             */
            doReset(){
                this.formData = this.getInitFormData();
                this.logicRoomList = [];
                this.id = null;
                if(this.$refs['formData']) this.$refs['formData'].resetFields();
            },
            /**
             * ActionTask ABNB API 同步
             */
            doSynchro(){
                const _this = this;
                if(!this.listingId){
                    _this.$message.error('PhysicalRoomListing id is null,Please Check Data...!');
                    return;
                }
                const actionName = "sync_calendar_to_airbnb";
                this.loadingText = "Calling API: "+actionName+" ...";
                this.loading = true;

                submitAction("PhysicalRoomListing", this.listingId,actionName).then(res => {
                    this.loading = false;
                    _this.$notify({
                        title: 'Success',
                        message: 'ListingId:'+ this.listingId+' call API:'+actionName+' succeeded !',
                        type: 'success'
                    });

                }).catch(reason => {
                    _this.loading = false;
                    console.log("deleteModel Failure...");
                    console.error(reason);
                    _this.$notify.error({
                        title: 'Error',
                        message: 'API:'+actionName+'  call error !'
                    });
                    //_this.$message.error('Please Check Input Form Data Has Errors!');
                });
            }
        }
    }
</script>

<style scoped>
  .input-size{
    width: 85%;
  }
  .form-item-wd{
    margin-right: 20px;
  }
</style>

